package com.demo.core.service.base.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import com.demo.core.dao.RecordDao;
import com.demo.core.dao.base.support.ResultSearchResult;
import com.demo.core.dao.base.support.SearchArgumentSupport;
import com.demo.core.model.Record;
import com.demo.core.service.base.RecordService;

/**
 * 站点审计服务实现类
 * 
 * @author ryuu.kk
 *
 */
public class RecordServiceImpl implements RecordService {

	/**
	 * 配置数据访问层Dao
	 */
	private RecordDao recordDao;
	
	@Override
	@Transactional
	public Long save(Record record) {
		Long id = recordDao.insert(record);
		return id;
	}
	
	@Override
	public boolean exists(Long id) {
		return recordDao.exists(id);
	}
	
	@Override
	public void delete(Long id) {
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("recordId", id);
		recordDao.delete(id);
	}
	
	@Override
	public void update(int count, Long objectId, int type) {
		Record r = new Record();
		r.setCount(count);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("objectId", objectId);
		params.put("type", type);
		recordDao.update(r, params);
	}

	@Override
	public void reset(Long siteId, Long objectId, String objectType, int count, byte type) {
		
		Record r = new Record();
		r.setCount(count);
		r.setSiteId(siteId);
		r.setType(type);
		r.setObjectType(objectType);
		r.setObjectId(objectId);
		r.setCount(count);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("objectId", objectId);
		params.put("type", type);
		List<Record> recordList = recordDao.select(params);
		if (recordList.size() > 0) {
			// 存在
			recordDao.update(r, params);
		} else {
			recordDao.insert(r);
		}
		recordList = null;
	}
	
	@Override
	public Record find(Long objectId, int type) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("objectId", objectId);
		params.put("type", type);
		List<Record> recordList = recordDao.select(params);
		return recordList.size() > 0 ? recordList.get(0) : null;
	}

	@Override
	public List<Record> findList(Long objectId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("objectId", objectId);
		return recordDao.select(params);
	}
	
	@Override
	public Record find(Long id) {
		return recordDao.select(id);
	}

	@Override
	public ResultSearchResult<Record> search(Long siteId, SearchArgumentSupport args) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("siteId", siteId);
		ResultSearchResult<Record> result = recordDao.search(params, args);
		return result;
	}
	
	public void setRecordDao(RecordDao recordDao) {
		this.recordDao = recordDao;
	}
}